package com.wwwarehouse.common.activity.media;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.media.ClipImageLayout;
import com.wwwarehouse.common.tools.FileUtils;

import static com.wwwarehouse.common.activity.media.SelectImageActivity.KEY_SELECT_IMAGE_PATH;

public class ClipImageActivity extends BaseActivity implements View.OnClickListener {
    private TextView mTopCancel, mTopOk;
    private ClipImageLayout mClipImageLayout;

    private FileUtils mFileUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clip_image);

        initView();
        initEvent();
    }

    private void initView() {
        Constant.isTakePhotoFinished = false;
        mTopCancel = findView(R.id.top_cancel);
        mTopOk = findView(R.id.top_ok);

        mClipImageLayout = findView(R.id.clip_image_layout);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String path = bundle.getString(KEY_SELECT_IMAGE_PATH);

            // OOM
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            mClipImageLayout.setImageDrawable(new BitmapDrawable(bitmap));
        }

        mFileUtils = new FileUtils();
    }

    private void initEvent() {
        mTopCancel.setOnClickListener(this);
        mTopOk.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.top_cancel) {
            finishActivity();
        } else if (id == R.id.top_ok) {
            Bitmap bitmap = mClipImageLayout.clip();

            //保存裁剪的图片
            String path = mFileUtils.saveImage(bitmap);

            Intent intent = new Intent();
            intent.putExtra(KEY_SELECT_IMAGE_PATH, path);
            setResult(RESULT_OK, intent);
            finishActivity();
        }
    }
}
